package com.apexsoft.monitor.front.console.aop;

import java.lang.reflect.Method;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.apexsoft.monitor.front.console.userlog.om.UserLog;
import com.apexsoft.monitor.front.console.userlog.service.UserLogService;
import com.apexsoft.front.common.utils.DateUtil;
import com.apexsoft.front.common.utils.SpringContextUtil;
import com.apexsoft.front.common.utils.SystemTool;
import com.apexsoft.front.common.utils.session.UserSessionNoRedis;

/**
 * 
* @ClassName: Aop 
* @Description: TODO(用户操作日志-AOP) 
* @author 码农
* @date 2016年6月7日 上午11:41:01 
* 
* 
	  .--,       .--,
	 ( (  \.---./  ) )
	  '.__/o   o\__.'
	     {=  ^  =}
	      >  -  <
	     /       \
	    //       \\
	   //|   .   |\\
	   "'\       /'"_.-~^`'-.
	      \  _  /--'         `
	    ___)( )(___
	   (((__) (__)))   
一直被模仿，从未被超越--XFH
 */
public class Aop {
	
    //Service层切点  
    @Pointcut("@annotation(com.apexsoft.monitor.front.console.aop.AopAnnotation)")
     public  void serviceAspect() {  
    }  
  
    //Controller层切点  
    @Pointcut("@annotation(com.apexsoft.monitor.front.console.aop.AopAnnotation)")
     public  void controllerAspect() {  
    }
    
	public void after(JoinPoint joinPoint){
		try { 
			 System.out.println("after请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));  
			 Object[] args = joinPoint.getArgs();
		        System.out.println("目标参数列表：");
		        if (args != null) {
		            for (Object obj : args) {
		                System.out.println(obj + ",");
		            }
		            System.out.println();
		        }
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	* @Title: afterReturn 
	* @Description: TODO(方法执行返回后面,到这个方法) 
	* @param @param point
	* @param @param returnObj    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	public void afterReturn(JoinPoint point, Object returnObj){
		try { 
			//取用户信息
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();    
			JSONObject userInfo = UserSessionNoRedis.getSessionObj(request, UserSessionNoRedis.CONSOLE_SESSION); 
			if (userInfo != null) {
				String de = getControllerMethodDescription(point);//注解 方法说明      @AopAnnotation(description="test-test")
				if(!"".equals(de)){
					String id = userInfo.getString("id");
					String name = userInfo.getString("name");
					String className = point.getTarget().getClass().getName();
					String method = point.getSignature().getName();
					//此方法返回的是一个数组，数组中包括request以及ActionCofig等类对象
					JSONObject params = new JSONObject();
			        Object[] args = point.getArgs();
			        String result  = "";
			        String ip=SystemTool.getIpAddr();
			        //result2Log  这个是反回信息的参数,如果需要记录返回信息,请在controller的方法里面将
			        //返回信息设置在 request里面
			        if (args != null) {
			        	if (method.equals("execBatchImportModuleMulit") || method.equals("importMulti")) {
			        		MultipartHttpServletRequest requestP = (MultipartHttpServletRequest) args[0];
			        		Enumeration enu=requestP.getParameterNames();  
				        	while(enu.hasMoreElements()){
				        		String paraName=(String)enu.nextElement();  
				        		params.put(paraName, requestP.getParameter(paraName));
				        	}
				        	result = (String)requestP.getAttribute("result2Log");
						}else{
				        	HttpServletRequest requestP = (HttpServletRequest)args[0];
				        	Enumeration enu=requestP.getParameterNames();  
				        	while(enu.hasMoreElements()){
				        		String paraName=(String)enu.nextElement();  
				        		String paraValue = requestP.getParameter(paraName);
				        		params.put(paraName, paraValue);
				        	}
				        	result = (String)requestP.getAttribute("result2Log");
						}
			        }
			        UserLog log = new UserLog();
			        log.setUserId(Integer.parseInt(id));
			        log.setUserName(name);
			        log.setIp(ip);
			        log.setClassName(className);
			        log.setMethod(method);
			        log.setParams(params.toJSONString());
			        log.setRemake(de);
			        log.setResult(result);
			        log.setCreateTime(DateUtil.getNowDateTime());
			        UserLogService userLogService = (UserLogService)SpringContextUtil.getBean("userLogService");
			        userLogService.addMonitorWargingInfo(log);
				}
		}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public  String getControllerMethodDescription(JoinPoint joinPoint)  throws Exception {  
		String description = "";  
		try{
        String targetName = joinPoint.getTarget().getClass().getName();  
        String methodName = joinPoint.getSignature().getName();  
        Object[] arguments = joinPoint.getArgs();  
        Class targetClass = Class.forName(targetName);  
        Method[] methods = targetClass.getMethods();  
        
         for (Method method : methods) {  
             if (method.getName().equals(methodName)) {  
                Class[] clazzs = method.getParameterTypes();  
                 if (clazzs.length == arguments.length) {  
                    description = method.getAnnotation(AopAnnotation.class).description();  
                     break;  
                }
            }
        }
		}catch(Exception e){}
         return description;  
    }  
}
